using System;
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEngine;

public class VoiceInputs : MonoBehaviour
{
    /// <summary>
    /// 录制的音频长度
    /// </summary>
    public int m_RecordingLength;

    public AudioClip recording;
    public AudioClip new_recording;
    public AudioClipCutter cutter;
    public List<AudioClip> audioClips;

    private float recordingStartTime; // 录音开始时间
    public bool ready;
    private void Update()
    {

    }

    /// <summary>
    /// WebGL辅助类
    /// </summary>
    [SerializeField] private SignalManager signalManager;
    /// <summary>
    /// 开始录制声音
    /// </summary>
    public void StartRecordAudio()
    {
#if UNITY_WEBGL && !UNITY_EDITOR
        signalManager.onAudioClipDone = null;
        signalManager.StartRecordBinding();
#else
        audioClips.Clear();
        recordingStartTime = Time.time; // 记录开始录音的时间
        recording = Microphone.Start(null, true, m_RecordingLength, 16000);

#endif
    }

    /// <summary>
    /// 结束录制，返回audioClip
    /// </summary>
    /// <param name="_callback"></param>
    public void StopRecordAudio(Action<AudioClip> _callback)
    {
        StartCoroutine(ieStopRecordAudio(_callback));
    }
    IEnumerator ieStopRecordAudio(Action<AudioClip> _callback)
    {
#if UNITY_WEBGL && !UNITY_EDITOR
        signalManager.onAudioClipDone += _callback;
        signalManager.StopRecordBinding();
#else

        float recordingLength = Time.time - recordingStartTime;
        // 创建一个新的AudioClip，将实际录音长度内的数据复制到新的音频片段中
        int recordingSamples = (int)(recordingLength * recording.frequency);
        new_recording = AudioClip.Create("TrimmedRecording", recordingSamples, recording.channels, recording.frequency, false);
        float[] data = new float[recording.samples];
        recording.GetData(data, 0);
        float[] trimmedData = new float[recordingSamples];
        Array.Copy(data, trimmedData, recordingSamples);
        new_recording.SetData(trimmedData, 0);
        Microphone.End(null);
        cutter.Cutter(new_recording);
        audioClips = cutter.audioClips;
        for (int i = 0; i < audioClips.Count; i++)
        {
           
            if(i==audioClips.Count-1)
            {
                ready = true;
            }
            else
            {
                ready = false;
            }
            _callback(audioClips[i]);
            yield return new WaitForSeconds(2);
        }


#endif

    }

}
